package com.nolon.flange.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.nolon.flange.R
import com.nolon.flange.databinding.ItemPieceBinding
import com.nolon.flange.databinding.ItemPieceHeaderBinding
import com.nolon.flange.model.FlangePartItem

class PieceAdapter(val acc: AppCompatActivity) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    var tableHeaderColor: Int =  ContextCompat.getColor(acc,R.color.table_1_header)
    var tableRowOddColor: Int =  ContextCompat.getColor(acc,R.color.table_1_row_1)
    var tableRowEvenColor: Int =  ContextCompat.getColor(acc,R.color.table_1_row_2)


    var partList = mutableListOf<FlangePartItem>()

    fun swapData(data: List<FlangePartItem>) {
        partList.clear()
        partList.addAll(data)
        notifyDataSetChanged()
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == HEADER_TYPE) {
            val binding =
                ItemPieceHeaderBinding.inflate(LayoutInflater.from(parent.context), parent, false)
            PieceHeaderViewHolder(binding)
        } else {
            val binding =
                ItemPieceBinding.inflate(LayoutInflater.from(parent.context), parent, false)
            PieceViewHolder(binding)
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (position == 0 && holder is PieceHeaderViewHolder) {
            holder.binding.layout.setBackgroundColor(tableHeaderColor)
        }
        if (position > 0 && holder is PieceViewHolder) {
            val part = partList[position - 1].part
            holder.binding.apply {
                textNumber.text = position.toString()
                textMaterialSpec.text = part.materialSpec.toString()
                textFlangeSpec.text = part.quantity.toString()
                textRounding.text =
                    if (part.rounding) acc.getString(R.string.yes) else acc.getString(R.string.no)
                textCount.text = partList[position - 1].requiredNum.toString()
                if (position.rem(2) == 0) {
                    layout.setBackgroundColor(tableRowEvenColor)
                } else {
                    layout.setBackgroundColor(tableRowOddColor)
                }
            }
        }
    }

    override fun getItemCount(): Int {
        return partList.size + 1
    }

    class PieceViewHolder(val binding: ItemPieceBinding) : RecyclerView.ViewHolder(binding.root)

    class PieceHeaderViewHolder(val binding: ItemPieceHeaderBinding) :
        RecyclerView.ViewHolder(binding.root)

    override fun getItemViewType(position: Int) = if (position == 0) HEADER_TYPE else CONTENT_TYPE

    companion object {
        const val HEADER_TYPE = 0
        const val CONTENT_TYPE = 1
    }

}